package com.shengdong.water.code.viewmodel

import com.shengdong.water.base.BaseViewModel
import com.shengdong.water.code.bean.Outlet
import com.shengdong.water.code.repository.ApiRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import javax.inject.Inject
import kotlin.collections.plus

@HiltViewModel
class SearchViewModel @Inject constructor(
    private val repository: ApiRepository
): BaseViewModel() {


    private val _outlets = MutableStateFlow<List<Outlet>>(emptyList())
    val outlets : StateFlow<List<Outlet>> = _outlets
    private var currentPage = 1
    private var isRefreshing = false

    fun getOutletList(name: String,current: Int, size: Int) {
        handlePagingRequest(
            flow = repository.getOutletList(name,current, size),
            showLoading = true,
            loading = "加载中...",
            onSuccess = { it ->
                _outlets.update { oldList ->
                    if (isRefreshing || currentPage == 1) {
                        isRefreshing = false
                        it
                    }else  {
                        oldList + it.filterNot { newItem ->
                            oldList.any { it.id == newItem.id }
                        }
                    }
                }

            },
            onError = { code, msg ->
                when (code) {
                    401 ->  {}// 处理未授权
                    403 -> {}// 处理禁止访问
                    else -> showError(msg)
                }

            },
            onException = {e ->
                showError("发生错误: ${e.message}")

            },
        )
    }

}